package com.jhh.pay.heli.processor;

import com.jhh.pay.heli.annotation.HeLiBaoApi;
import com.jhh.pay.heli.annotation.HeLiBaoService;
import com.jhh.pay.heli.constant.BaseConfig;
import com.jhh.pay.heli.constant.Constant;
import com.jhh.pay.heli.factory.RetrofitBeanFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * Created by zhangqi on 2017/12/4.
 *
 * 用来注入 Api接口
 */

@EnableConfigurationProperties
@Component
public class RetrofitAutowiredProcessor extends InstantiationAwareBeanPostProcessorAdapter {

    private Logger logger = LoggerFactory.getLogger(RetrofitAutowiredProcessor.class);

    @Autowired
    BaseConfig baseConfig;

    @Override
    public boolean postProcessAfterInstantiation(final Object bean, final String beanName) throws BeansException {
        ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                HeLiBaoService httpApi = field.getAnnotation(HeLiBaoService.class);
                if (httpApi == null) {
                    return;
                }
                createRetrofitService(bean, field, field.getType());
            }
        });
        return super.postProcessAfterInstantiation(bean, beanName);
    }

    private void createRetrofitService(Object bean, Field field, Class clazz) throws IllegalAccessException {

        HeLiBaoApi httpApi = (HeLiBaoApi) clazz.getAnnotation(HeLiBaoApi.class);

        /**
         * timeout 超时时间配置
         */
        int[] timeout = httpApi.timeOut();
        String value = httpApi.value();
        /**
         * 解析baseUrl 默认代付接口
         */
        String baseUrl = baseConfig.getBaseUrlPay();
        switch (value){
            case Constant.DAIFU:
                baseUrl = baseConfig.getBaseUrlPay();
                break;
            case Constant.DAIKOU:
                baseUrl = baseConfig.getBaseUrlWithhold();
                break;
        }
        logger.info("注入实体bean"+clazz.getName()+"-"+baseUrl);
        Object object = RetrofitBeanFactory.putBean(baseUrl,timeout, clazz,httpApi.interceptor());
        if (object == null) {
            return;
        }

        field.setAccessible(true);
        field.set(bean, object);
    }
}
